<template>
  <div class="makeAnAppointment">
    <div class="instructions">
      
      <p>预约说明：周一至周六 08:00-16:00</p>
      <div class="clearfix">
        <div class="fl">
          <span class="color"></span>
          <span>可预约</span>
        </div>
        <div class="fl">
          <span class="color"></span>
          <span>已预约</span>
        </div>
        <div class="fl">
          <span class="color"></span>
          <span>预约已满</span>
        </div>
      </div>
    </div>
    <van-calendar
      title
      :show-subtitle="false"
      :show-mark="false"
      :poppable="false"
      :show-confirm="false"
      :min-date='minDate'
      :max-date='maxDate'
      :style="{ height: '330px' }"
      row-height='40'
      :formatter="formatter"
      @select='dateClick'
      color="#e0e0e0"
      :class="{bg:activeColor}"
    />
    <van-tabs v-model="active" @change="tabsClick">
      
        <van-tab title="上午">
          <div class="box" v-if="conventionTime.times">
            <div v-if="loading" class="loading"><van-loading size="24px" vertical>加载中...</van-loading></div>
            <div
              v-for="(item,index) in timeObj"
              :key="item.id"
              class="times"
              @click="timeClick(item,index)"
              :class="{active:conventionTime.timeId === item.id,disabled:item.disabled,haveActive:item.have}"
            >
              <p v-if="!item.disabled">{{item.timeSub}}</p>
              <p v-else>预约已满</p>
            </div>
          </div>
          <div v-else class="tips">
            请选择日期
          </div>
        </van-tab>
        <van-tab title="下午">
          <div class="box" v-if="conventionTime.times">
            <div v-if="loading" class="loading"><van-loading size="24px" vertical>加载中...</van-loading></div>
            <div
              v-for="(item,index) in timeObj"
              :key="item.id"
              class="times"
              @click="timeClick(item,index)"
              :class="{active:conventionTime.timeId === item.id,disabled:item.disabled,haveActive:item.have}"
            >
              <p v-if="!item.disabled">{{item.timeSub}}</p>
              <p v-else>预约已满</p>
            </div>
          </div>
          <div v-else class="tips">
            请选择日期
          </div>
        </van-tab>
      
    </van-tabs>
    
    <van-button color="#27b5a7" :loading="uploading" @click="createOrder">提交预约</van-button>
    <foot :navUrl="url"/>
  </div>
</template>

<script>
import foot from '@/views/footer.vue'
import { getDateStr, time_range, getDate } from '@/utils/index'
import { rest,jobs } from '@/utils/day'
import { getLocal, setLocal } from '@/utils/storage'
import 'swiper/dist/css/swiper.css'
export default {
  name: 'makeAnAppointment',
  data() {
    return {
      activeColor:true,
      url:'vehicleInfo',
      minDate:new Date(new Date().setDate(new Date().getDate() + 1)),
      maxDate: new Date(new Date().setDate(new Date().getDate() + 15)),
      active: 0,
      // swiper 时间
      dateList: [],
      timeObj:{},
      carInfo: {},
      // 预约车检
      conventionTime: {
        // 时间段
        timeId: '',
        //times: getDateStr(1),
        times:null,
        index: null
      },
      interval:1,
      loading:true,
      uploading:false,
      // 用户信息
      carUser: JSON.parse(getLocal('userInfo')),
    }
  },
  created() {
    
    if (new Date().getDay() === 6) {
      this.minDate = new Date(new Date().setDate(new Date().getDate() + 2))
      //this.conventionTime.times = getDateStr(2)
    }
    console.log('this.conventionTime',this.conventionTime)
    //this.queryCarTime(this.conventionTime.times,this.interval)

    
  },
  mounted() {
    document.getElementsByTagName('html')[0].style.backgroundColor = '#f5f6f5'
  },
  methods: {
    // 预约时间
    async queryCarTime(date,Interval) {
      let carInfo = null
      console.log('this.$route.params.carInfo',this.$route.params.carInfo)
      if (this.$route.params.carInfo) {
        carInfo = this.$route.params.carInfo
        let parse = {
          stationId: 1,
          date:date,
          Interval:Interval,
          userId: this.carUser.id,
          carId: carInfo.id
        }
        if (carInfo.type === 2) {
          parse.carId = carInfo.carId
        }
        let { data,status } = await this.$api.queryCarTime(parse)
        this.loading = false
        if (status === 200) {
          console.log(data.list,status,'---------data.data.list---------')
          this.timeObj = data.list.map(el => {
            if (el.status === 0) {
              el.disabled = true
            }
            if (el.status === 2) {
              el.have = true
            }
            return el
          })
        }
      }else{
        this.$toast('请重新选取车辆');
        this.$router.go(-1);
      }
      console.log(this.timeObj, date, '----------预约时间-----------')
      /* this.conventionTime.times = date

      let forbiddenTime = JSON.parse(getLocal('forbiddenTime')) */

      /* if (data && data.list) {
        this.timeArr = data.list.map(el => {
          if (forbiddenTime) {
            forbiddenTime.map(els => {
              if (date === els.times && els.timeId === el.id) {
                el.timeNum--
              }
            })
          }
          let [start, end] = el.timeSub.split('-')
          if (!time_range(start, end, date)) {
            el.disabled = true
          }
          return el
        })
      } */
    },
    // 提交预约
    async createOrder() {
      if (this.$route.params.carInfo) {
        let carInfo = this.$route.params.carInfo
        let params = {}
        params = {
            stationId: 1,
            type: carInfo.type,
            times: this.conventionTime.times,
            Interval:this.interval,
            timeId: this.conventionTime.timeId,
            userId: carInfo.userId,
            
          }
        console.log(carInfo.type === 1)
        if (carInfo.type === 1) {

          params.carId=carInfo.id
          params.userSign=carInfo.carAttachment1
        } else {
          console.log(carInfo)
          params.carId=carInfo.carId
          params.id=carInfo.id
          params.userSign=carInfo.userSign
          //params.createTime = this.formatStyle(carInfo.createTime)
          params.appointments = carInfo.appointments
        }
        if (params.timeId === '' || params.timeId === null) {
          this.$toast('请选择正确时间段')
        }else{
          this.uploading = true
          console.log(params)
          let res = await this.$api.createOrder(params)
          this.uploading = false
          console.log(res, '------------提交预约 res--------------')
          if (res.status === 200) {
            if (res.data.type === 2) {
              this.$router.push('/')
              this.$toast('修改成功')
            }else{
              this.$router.push({
                name: 'orderPay',
                params: {
                  carInfo: res.data
                }
              })
            }
          }
        }

      }else{
        this.$toast('请重新选取车辆');
        this.$router.push('/vehicleInfo');
      }
      
      /* if (params.timeId === '' || params.timeId === null) {
        this.$toast('请选择正确时间段')
      }else{
        this.$router.push({
          name: 'vehicleInfo',
          params: {
            state: 'convention',
            conventionParams: params
            // vehicleList: this.vehicleList
          }
        })
      }
      

      console.log(params, '--------提交预约params------') */
      
      
    },
    // 时间点击
    timeClick(item, index) {
      console.log('item=',item,'index=',index,this.active)
      if (item.status === 0 ) {
        this.$toast('当前预约人数已满');
        this.conventionTime.timeId = null
      }else if (item.status === 2 ) {
        this.$toast('当前已预约');
        this.conventionTime.timeId = null
      }else{
        this.conventionTime.timeId = item.id
        this.conventionTime.index = index
      }
      
      // if (item.disabled) {
      //   return this.$toast('只可预约当前相邻时间哦')
      // }
      // if (!item.timeNum) {
      //   return this.$toast('无法预约')
      // } else {
      //   this.conventionTime.timeId = item.id
      //   this.conventionTime.index = index
      // }
    },
    //点击日期
    dateClick(date){
      let Y = date.getFullYear()
      let M = (date.getMonth()+1)>9?(date.getMonth()+1):'0'+(date.getMonth()+1)
      let D = (date.getDate()>9?date.getDate():'0'+date.getDate())
      this.conventionTime.times = Y+'-'+M+'-'+D
      this.loading = true
      this.timeObj={}
      this.activeColor = false
      this.queryCarTime(this.conventionTime.times,this.interval)
    },
    //上下午切换
    tabsClick(name, title){
      console.log(name,title)
      this.interval = name+1
      this.loading = true
      this.timeObj={}
      this.queryCarTime(this.conventionTime.times,this.interval)
    },
    formatter(day) {
      let d = new Date(day.date).getDate();
      let m = new Date(day.date).getMonth();
      if (day.date.getDay() === 0) {
        jobs.forEach(item=>{
          let dd = new Date(item).getDate()
          let mm = new Date(item).getMonth()
          if (dd === d && mm === m) {
            day.type = ''
          }else{
            day.type = 'disabled'
          }
        })
      }
      rest.forEach(item=>{
        let dd = new Date(item).getDate()
        let mm = new Date(item).getMonth()
        if (dd === d && mm === m) {
          day.type = 'disabled'
        }
      })
      return day
    },
    formatStyle(v){
      let date = new Date(v)
      let Y = date.getFullYear()
      let M = date.getMonth()+1
      let D = date.getDate()
      let h = date.getHours()
      let m = date.getMinutes()
      let s = date.getSeconds()
      if (M<10) {
        M = '0'+M
      }
      if (D<10) {
        D = '0'+D
      }
      if(h<10){
        h = '0'+h
      }
      if(m<10){
        m = '0'+m
      }
      if(s<10){
        s = '0'+s
      }
      console.log(Y,M,D,h,m,s)
      return Y+'/'+M+'/'+D+' '+h+':'+m+':'+s
    }
  },
  beforeRouteLeave(to, from, next) {
    document.getElementsByTagName('html')[0].style.backgroundColor = '#fff'
    next()
  },
  components: {
    foot
  }
}
</script>

<style lang="less" scoped>

.tips{
  text-align: center;
  font-size: 0.4rem;
  line-height: 1rem;
  width: 100%!important;
}
.makeAnAppointment {
  // padding-top: 0.427rem;
  
  .loading{
    width: 100%;
    text-align: center;
  }
  // 选择时间
  .chooseTime {
    display: flex;
    flex-wrap: wrap;
    margin-top: 0.4rem;
    padding: 0 0.227rem;
    div {
      width: 31%;
      height: 2rem;
      flex-grow: 1; /* 子元素按1/n的比例进行拉伸 */
      background-color: #f8f8f8;
      text-align: center;
      margin-right: 0.24rem;
      margin-bottom: 0.307rem;
      text-align: center;
      line-height: 0.64rem;
      font-size: 0.333rem;
      padding-top: 0.107rem;
      color: #7c7c7c;
      .col {
        color: #000;
        span:nth-of-type(2) {
          color: #eb382f;
        }
      }
      p {
        span {
          span {
            display: inline-block;
            margin: 0 0.053rem;
          }
        }
      }
    }

    .active {
      background-color: #eee;
    }
    .disabled {
      background-color: #e1e1e1;
      opacity: 0.2;
      .col {
        span:nth-of-type(2) {
          color: #333;
        }
      }
    }
    div:nth-of-type(3n) {
      /* 选择个数是3的倍数的元素 */
      margin-right: 0;
    }
    div:nth-of-type(n + 16) {
      /* 选择倒数的三个元素，n可以取0 */
      margin-bottom: 0;
    }
  }

  // 预约说明
  .instructions {
    width: 90%;
    background-color: #fff;
    border-radius: 0.267rem;
    margin: 0.267rem auto 0.4rem;
    padding: 5% 0;
    p {
      text-align: center;
      font-size: 0.373rem;
      margin-bottom: 5%;
    }

    .clearfix {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
      div {
        width: 30%;
        span:nth-of-type(1) {
          width: 0.8rem;
          height: 0.453rem;
          margin-right: 0.133rem;
        }
        span {
          font-size: 0.373rem;
          float: left;
          
        }
      }
      div.fl:nth-of-type(1) .color {
        border: 1px solid #000;
        background-color: #cdf1cd;
      }
      div.fl:nth-of-type(2) .color {
        background-color: #ff8d27;
      }
      div.fl:nth-of-type(3) .color {
        background-color: #ff0016;
      }
    }
  }
  // 选择时间
  .van-tabs__content {
    .van-tab__pane {
      .box{
        display: flex;
        flex-wrap: wrap;
        // justify-content: space-around;
        justify-content: space-between;
      }
    }
    .times {
      width: 31%;
      height: 0.8rem;
      line-height: 0.8rem;
      margin-top: 5%;
      text-align: center;
      border: 1px solid #295cc0;
      border-radius: 0.107rem;
      margin-top: 0.267rem;
      background-color:#cdf1cd;
    }
    .active {
      background-color: #e4ca4c;
    }
    .haveActive {
      background-color: #ff8d27;
      color: #fff;
    }
    .disabled {
      background-color: #ff0016;
      color: #fff;
    }
  }

  .van-button {
    width: 90%;
    display: block;
    margin: 1.227rem auto ;
    border-radius: 0.16rem;
    font-size: 0.613rem;
    font-weight: 600;
  }
}
</style>
